package cn.com.dingtek.genius.manager.server.support.sam;

import cn.com.dingtek.genius.manager.server.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.jwt.crypto.sign.SignerVerifier;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface Authenticator {
    String SECURITY_AUTH_KEY = "identity_token";
    SignerVerifier signerVerifier = new MacSigner("genius");

    String cookieName = SECURITY_AUTH_KEY;
    int tokenValiditySeconds = -1;

    static boolean isLogin(HttpServletRequest request) {
        String cookie = CookieUtil.extractCookie(SECURITY_AUTH_KEY, request);
        if (StringUtils.isBlank(cookie)) {
            return false;
        }

        SamToken token = SamToken.decodeAndVerify(cookie, signerVerifier);
        if (token == null) {
            return false;
        }

        SecurityContextHolder.setContext(SecurityContext.builder().token(token).build());
        return true;
    }

    static String tokenToCookie(HttpServletRequest request, HttpServletResponse response, SamToken token) {
        String cookieValue = token.encode(signerVerifier);
        CookieUtil.putCookie(cookieName, cookieValue, tokenValiditySeconds, request, response);
        return cookieValue;
    }
}
